<template>
  <div class="ap">
    <!-- 富文本编辑器 -->
    <div class="from">
      <input type="text" placeholder="标题" v-model="title" /><br />
      <input type="text" placeholder="图片url" v-model="imgurl" />
    </div>
    <p>这里是正文</p>
    <!-- CHANGE: Update the component tag and props -->
    <QuillEditor
      v-model:content="richTextContent"
      :options="editorOptions"
      theme="snow"
      ref="myQuillEditor"
      style="min-height: 300px;" 
    />
    <!-- 保存按钮 -->
    <!-- ... rest of your template ... -->
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
// 导入新的富文本编辑器组件和样式
import { QuillEditor } from '@vueup/vue-quill';
import '@vueup/vue-quill/dist/vue-quill.snow.css';



    // 定义数据
    const title = ref('');
    const imgurl = ref('');
    const richTextContent = ref(''); // This is now bound via v-model:content

    // CHANGE: Update options - remove theme as it's a separate prop now
    const editorOptions = ref({ // Using ref for options is good practice if they might change
        placeholder: "请输入你想发布的内容",
        // theme: "snow", // Remove theme from options, it's a prop now
        modules: {
             toolbar: [ // Example: Add a basic toolbar if you want one explicitly
                ['bold', 'italic', 'underline', 'strike'],
                [{ 'list': 'ordered'}, { 'list': 'bullet' }],
                ['link', 'image'], // Add image button if needed
                ['clean']
             ]
        }
    });

    const myQuillEditor = ref(null); // Ref for accessing the editor instance if needed

    // Your existing methods (saveToDatabase, goToIndexPage, updateTime) should work as before
    // as they mainly rely on the `richTextContent` ref.

    const saveToDatabase = async () => {
        // Use the content directly from the ref
        const contentToSend = richTextContent.value;

        // Ensure you handle potential null/undefined from sessionStorage
        const shangData = sessionStorage.getItem("shang");
        const parsedObject = shangData ? JSON.parse(shangData) : null;

        if (!parsedObject || !parsedObject.id) {
            console.error('User data not found in sessionStorage or missing ID.');
            // Handle error appropriately (e.g., show message to user)
            return;
        }

        // Ensure title is provided if required
        if (!title.value) {
             console.error('Title is required.');
             // Handle error
             return;
        }

        const formattedDateString = updateTime().replace(' ', 'T'); // Consider server time if accuracy is critical

        const data = {
            // id: null, // Usually handled by the database (auto-increment)
            author_id: parsedObject.id,
            title: title.value,
            url: imgurl.value || null, // Send null if empty
            content: contentToSend,
            time: formattedDateString, // Send as ISO string
            // views: null // Usually set by backend or defaults to 0
        };

        console.log("Sending data:", data);

        try {
            const response = await fetch('/backend/article/insert', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(data)
            });

            if (response.ok) {
                console.log('保存成功');
                const result = await response.json(); // Optional: get response data
                console.log('Server response:', result);
                // Optionally clear fields or navigate away
                // title.value = '';
                // imgurl.value = '';
                // richTextContent.value = ''; // Or use editor's API if available via ref
                // goToIndexPage();
            } else {
                console.error('保存失败 - Status:', response.status);
                const errorText = await response.text(); // Get error details from backend
                console.error('Server error message:', errorText);
                // Show error message to user
            }
        } catch (error) {
            console.error('保存请求失败:', error);
            // Show network or other error message to user
        }
    };

    const goToIndexPage = () => {
        // You need access to the router instance.
        // If this component is directly used by <router-view>, you can import `useRouter`
        // import { useRouter } from 'vue-router';
        // const router = useRouter();
        // router.push('/header/index');
        console.warn("Router not implemented in this snippet. Implement useRouter if needed.");
    };

    const updateTime = () => {
        const now = new Date();
        // Use toISOString and slice for a standard format, easily parsed by most backends
        // return now.toISOString(); // Format: 2023-10-27T10:30:00.123Z (UTC)
        // Or your specific format if required:
        const year = now.getFullYear();
        const month = ('0' + (now.getMonth() + 1)).slice(-2);
        const day = ('0' + now.getDate()).slice(-2);
        const hours = ('0' + now.getHours()).slice(-2);
        const minutes = ('0' + now.getMinutes()).slice(-2);
        const seconds = ('0' + now.getSeconds()).slice(-2);
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`; // Keep local time if needed
    };

    // onMounted(() => {
        // If you need to access the Quill instance directly after mount:
        // console.log(myQuillEditor.value?.getQuill());
    // });

</script>

<style scoped>
	.app {
		width: 100vw;
		height: 100vh;
		background-color: #ccc;
		margin: 0 auto;
	}

	.display-area {
		margin-top: 20px;
		border: 1px solid #ccc;
		padding: 10px;
	}

	.btn {
		width: 80%;
		height: 100px;
		/* background-color: aliceblue; */
		margin: auto;
		display: flex;
		align-items: center;
	}

	.qu {
		position: absolute;
		left: 20%;
	}

	.mit {
		position: absolute;
		right: 20%;
	}

	.from {
		display: flex;
		width: 800px;
		height: 50px;
		margin: auto;
		/* background-color: aqua; */
	}

	.from input {
		width: 300px;
		height: 30px;
		margin: 8px 50px 0px auto;
		color: #000;

	}
</style>